#pragma once

#include <vector>
#include <queue>
#include <pthread.h>
#include <functional>
#include <pthread.h>
#include <iostream>

#include "Thread.hpp"
#include "Log.hpp"

using namespace log_ns;

static const int defaultnum = 5;

using func_t = std::function<void()>;

template <typename T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool IsEmpty()
    {
        return _task_queue.empty();
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void WakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    void Join()
    {
        for (auto &e : _threads)
        {
            e.Join();
        }
        LOG(DEBUG, "Join success\n");
        // std::cout << "Join success" << std::endl;
    }

    ThreadPool(int num = defaultnum)
        : _thread_num(num), _sleep_thread_num(0), _isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ThreadPool &operator=(const ThreadPool<T> &) = delete;
    ThreadPool(const ThreadPool<T> &) = delete;

public:
    static ThreadPool<T> *GetInstance()
    {
        if (_tp == nullptr)
        {
            LockGuard lockguard(&_sig_mutex);
            if (_tp == nullptr)
            {
                LOG(DEBUG, "Create ThreadPool\n");
                _tp = new ThreadPool();
                _tp->Init();
                _tp->Start();
            }
        }
        return _tp;
    }

    ~ThreadPool()
    {
        Join();
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    void Equeue(const T &in)
    {
        LockQueue();
        if (_isrunning)
        {
            _task_queue.push(in);
            if (_sleep_thread_num > 0)
            {
                Wakeup();
            }
        }
        UnlockQueue();
        LOG(DEBUG, "Equeue a task\n");
        // std::cout << "Equeue a task" << std::endl;
    }

    void HanderTask()
    {
        while (true)
        {
            T t;
            LockQueue();
            if (IsEmpty() && _isrunning)
            {
                _sleep_thread_num++;
                Sleep();
                _sleep_thread_num--;
            }
            if (IsEmpty() && !_isrunning)
            {
                UnlockQueue();
                break;
            }

            t = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();

            // 执行任务
            t();
            // LOG(DEBUG, "%s\n", t.result().c_str());
        }
    }

    void Start()
    {
        _isrunning = true;

        for (int i = 0; i < _thread_num; i++)
        {
            _threads[i].Start();
        }
        LOG(DEBUG, "Start success\n");
        // std::cout << "Start success" << std::endl;
    }

    void Init()
    {
        func_t func = std::bind(&ThreadPool::HanderTask, this);
        for (int i = 0; i < _thread_num; i++)
        {
            _threads.emplace_back(func);
        }
        LOG(DEBUG, "Init success\n");
        // std::cout << "Init success" << std::endl;
    }

    void Stop()
    {
        LockQueue();
        _isrunning = false;
        WakeupAll();
        UnlockQueue();
        LOG(DEBUG, "Stop Success\n");
        // std::cout << "Stop Success" << std::endl;
    }

private:
    int _thread_num;
    int _sleep_thread_num;
    // std::vector<Thread> _threadpool;
    std::vector<Thread> _threads;
    std::queue<T> _task_queue;
    bool _isrunning;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

template <typename T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <typename T>
pthread_mutex_t ThreadPool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;